// 微信小游戏入口文件

// 游戏画布
const canvas = wx.createCanvas();
const ctx = canvas.getContext('2d');

// 获取系统信息
const systemInfo = wx.getSystemInfoSync();
const screenWidth = systemInfo.windowWidth;
const screenHeight = systemInfo.windowHeight;

// 设置画布尺寸
canvas.width = screenWidth;
canvas.height = screenHeight;

// 游戏状态
let gameState = 'start'; // start, playing, over
let score = 0;
let timeLeft = 30; // 游戏时间30秒

// 资源加载
const images = {};
const imageList = [
  { name: 'bg', src: 'img/bg.jpg' },
  { name: 'board', src: 'img/board2.jpg' },
  { name: 'bucket', src: 'img/bucket.png' },
  { name: 'personFs', src: 'img/person-fs.png' },
  { name: 'personFsWet', src: 'img/person-fs-wet.png' },
  { name: 'personLdh', src: 'img/person-ldh.png' },
  { name: 'personLdhWet', src: 'img/person-ldh-wet.png' },
  { name: 'personLj', src: 'img/person-lj.png' },
  { name: 'personLjWet', src: 'img/person-lj-wet.png' },
  { name: 'start', src: 'img/start.jpg' },
  { name: 'waterFull', src: 'img/water-full.png' },
  { name: 'shareTip', src: 'img/share_tip.png' }
];

// 角色配置
const characters = [
  { type: 'fs', normal: 'personFs', wet: 'personFsWet', score: 1 },
  { type: 'ldh', normal: 'personLdh', wet: 'personLdhWet', score: 1 },
  { type: 'lj', normal: 'personLj', wet: 'personLjWet', score: 1 }
];

// 游戏配置
const config = {
  holeCount: 9,  // 洞口数量
  showTime: 1000, // 角色显示时间(ms)
  minInterval: 500, // 最小出现间隔(ms)
  maxInterval: 1500 // 最大出现间隔(ms)
};

// 洞口位置
const holes = [];

// 当前显示的角色
let activeCharacters = [];

// 加载进度
let loadedCount = 0;
let totalResources = imageList.length;

// 加载图片资源
function loadResources() {
  imageList.forEach(item => {
    const image = wx.createImage();
    image.src = item.src;
    image.onload = () => {
      images[item.name] = image;
      loadedCount++;
      
      // 更新加载进度
      const progress = Math.floor((loadedCount / totalResources) * 100);
      drawLoading(progress);
      
      // 所有资源加载完成
      if (loadedCount >= totalResources) {
        initGame();
      }
    };
    image.onerror = () => {
      console.error('Failed to load image:', item.src);
    };
  });
}

// 绘制加载界面
function drawLoading(progress) {
  ctx.fillStyle = 'rgba(0, 0, 0, 0.6)';
  ctx.fillRect(0, 0, screenWidth, screenHeight);
  
  ctx.fillStyle = '#ffffff';
  ctx.font = '20px Arial';
  ctx.textAlign = 'center';
  ctx.fillText(`疯狂载入中... [${progress}%]`, screenWidth / 2, screenHeight / 2);
}

// 初始化游戏
function initGame() {
  // 计算洞口位置
  const holeSize = screenWidth / 3;
  
  for (let i = 0; i < config.holeCount; i++) {
    const row = Math.floor(i / 3);
    const col = i % 3;
    holes.push({
      x: col * holeSize + holeSize / 2,
      y: row * holeSize + (screenHeight / 2 - row*10),
      radius: holeSize / 2
    });
  }
  console.log(holes);
  
  // 显示开始界面
  drawStartScreen();
  
  // 监听触摸事件
  wx.onTouchStart(handleTouch);
}

// 绘制开始界面
function drawStartScreen() {
  if (images.start) {
    ctx.drawImage(images.start, 0, 0, screenWidth, screenHeight);
  }
}

// 开始游戏
function startGame() {
  gameState = 'playing';
  score = 0;
  timeLeft = 30;
  activeCharacters = [];
  
  // 开始游戏循环
  gameLoop();
  
  // 开始计时器
  const timer = setInterval(() => {
    timeLeft--;
    if (timeLeft <= 0) {
      clearInterval(timer);
      endGame();
    }
  }, 1000);
}

// 生成新角色
function generateCharacter() {
  // 在最后10秒允许同时出现两只螃蟹
  if (activeCharacters.length >= (timeLeft <= 15 ? 2 : 1)) return;
  
  // 随机选择一个洞口
  const holeIndex = Math.floor(Math.random() * holes.length);
  
  // 随机选择一个角色类型
  const characterType = characters[Math.floor(Math.random() * characters.length)];
  
  // 创建新角色
  const hole = holes[holeIndex];
  
  const newCharacter = {
    holeIndex,
    type: characterType.type,
    state: 'normal', // normal, wet
    score: characterType.score,
    showTime: config.showTime,
    timeLeft: config.showTime,
    startY: hole.y, // 初始Y坐标
    targetY: hole.y - 20, // 目标Y坐标
    progress: 0 // 动画进度
  };
  
  activeCharacters.push(newCharacter);
}

// 游戏主循环
function gameLoop() {
  if (gameState !== 'playing') return;
  
  // 清空画布
  ctx.clearRect(0, 0, screenWidth, screenHeight);
  
  // 绘制背景
  if (images.bg) {
    ctx.drawImage(images.bg, 0, 0, screenWidth, screenHeight);
  }
  
  // 绘制角色
  drawCharacters();
  
  // 绘制UI
  drawUI();
  
  // 根据剩余时间调整生成概率
  const generateProbability = timeLeft <= 10 ? 0.3 : 0.2;
  if (Math.random() < generateProbability && activeCharacters.length < (timeLeft <= 10 ? 2 : 1)) {
    generateCharacter();
  }
  
  // 更新角色状态
  updateCharacters();
  
  // 继续游戏循环
  requestAnimationFrame(gameLoop);
}

// 更新角色状态
function updateCharacters() {
  const now = Date.now();
  
  // 更新每个角色的状态
  activeCharacters.forEach(char => {
    char.timeLeft -= 16; // 假设60fps，每帧约16ms
    
    // 更新动画进度
    if (char.progress < 1) {
      char.progress = Math.min(1, char.progress + 0.05); // 控制上升速度
    }
    
    if (char.timeLeft <= 0) {
      // 角色消失
      activeCharacters = activeCharacters.filter(c => c !== char);
    }
  });
}

// 绘制角色
function drawCharacters() {
  activeCharacters.forEach(char => {
    const hole = holes[char.holeIndex];
    const characterConfig = characters.find(c => c.type === char.type);
    
    if (!characterConfig) return;
    
    const imageName = char.state === 'normal' ? characterConfig.normal : characterConfig.wet;
    const image = images[imageName];
    
    if (image) {
      const size = hole.radius * 2;
      // 使用线性插值计算当前Y坐标
      const currentY = char.startY + (char.targetY - char.startY) * char.progress;
      ctx.drawImage(image, hole.x - size/2, currentY - size/2, size, size);
    }
  });
}

// 绘制UI
function drawUI() {
  // 绘制时间
  ctx.fillStyle = '#ffffff';
  ctx.font = '34px Arial';
  ctx.textAlign = 'left';
  ctx.fillText(`${timeLeft}"`, 60, 124);
  
  // 绘制分数
  ctx.fillStyle = '#0000ff';
  ctx.font = '60px Arial';
  ctx.fillText(`${score}`, screenWidth - 138, 164);
}

// 处理触摸事件
function handleTouch(e) {
  const touch = e.touches[0];
  const x = touch.clientX;
  const y = touch.clientY;
  
  if (gameState === 'start') {
    // 开始游戏
    startGame();
    return;
  }
  
  if (gameState === 'over') {
    // 检查是否点击了重新开始按钮
    const retryBtnY = screenHeight * 0.58;
    const shareBtnY = screenHeight * 0.7;
    const btnWidth = screenWidth * 0.67;
    const btnHeight = screenHeight * 0.1;
    const btnLeft = screenWidth * 0.17;
    
    if (x >= btnLeft && x <= btnLeft + btnWidth) {
      if (y >= retryBtnY && y <= retryBtnY + btnHeight) {
        // 重新开始
        startGame();
        return;
      } else if (y >= shareBtnY && y <= shareBtnY + btnHeight) {
        // 分享
        shareGame();
        return;
      }
    }
    return;
  }
  
  // 游戏中 - 检查是否击中角色
  activeCharacters.forEach(char => {
    const hole = holes[char.holeIndex];
    const distance = Math.sqrt(Math.pow(x - hole.x, 2) + Math.pow(y - hole.y, 2));
    
    if (distance <= hole.radius && char.state === 'normal') {
      // 击中角色
      char.state = 'wet';
      score += char.score;
      
      // 设置角色消失时间
      char.timeLeft = 500; // 0.5秒后消失
    }
  });
}

// 结束游戏
function endGame() {
  gameState = 'over';
  
  // 绘制结束界面
  if (images.board) {
    ctx.drawImage(images.board, 0, 0, screenWidth, screenHeight);
  }
  
  // 显示分数
  ctx.fillStyle = '#56261e';
  ctx.font = '36px Arial';
  ctx.textAlign = 'center';
  ctx.fillText(`${score}分`, screenWidth / 2, screenHeight * 0.3);

  // 显示等级
  let level = '';
  if (score < 30) {
    level = '初级捕蟹手';
  } else if (score < 60) {
    level = '捕蟹专业户';
  } else {
    level = '捕蟹神中神';
  }
  
  ctx.fillStyle = '#56261e';
  ctx.font = '32px Arial';
  ctx.fillText(level, screenWidth / 2, screenHeight * 0.5);
}

// 分享游戏
function shareGame() {
  // if (images.shareTip) {
  //   ctx.drawImage(images.shareTip, 0, 0, screenWidth, screenHeight);
  // }
  
  // 调用微信分享API
  wx.shareAppMessage({
    title: '蟹黄丰满，吃货来袭，越抓越上瘾！',
    imageUrl: 'img/share.jpg' // 分享图片
  });
}

// 开始加载资源
loadResources();